package com;


import com.example.grpc.HelloRequest;
import com.example.grpc.HelloResponse;
import com.example.grpc.HelloServiceGrpc;
import com.interceptor.HeaderClientInterceptor;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.util.concurrent.TimeUnit;

/**
 * 流式风格异步 RPC 调用
 * <p>
 * https://www.it610.com/article/1187569323888189440.htm
 */
public class StreamObserverGrpcClient {
    public static void main(String[] args) throws InterruptedException {

        /**
         * redis 缓存：
         *
         * job_id_1   '127.0.0.1:9091'
         * job_id_2   '127.0.0.1:9092'
         */

        // 客户端连接通道
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8081)
                .usePlaintext(true)
                .build();

        HelloServiceGrpc.HelloServiceStub stub = HelloServiceGrpc.newStub(channel);


        for (int i = 1; i < 2; i++) {
            HelloRequest helloRequest = HelloRequest.newBuilder()
                    .setName("Tom")
                    .setAge(i)
                    .addHobbies("read")
                    .putTags("boy", "money")
                    .build();

            int finalI = i;
            StreamObserver<HelloResponse> responseObserver = new StreamObserver<HelloResponse>() {
                public void onNext(HelloResponse value) {
                    // 解析成功结果
                    System.out.println(value);
                }

                public void onError(Throwable t) {
                    t.printStackTrace();
                }

                public void onCompleted() {
                    System.out.printf("第 %d 次结果已经传输完成！", finalI);
                }
            };

            stub.withInterceptors(new HeaderClientInterceptor())
                    .hello(helloRequest, responseObserver);
        }

        // 防止进程过早退出
        TimeUnit.SECONDS.sleep(5);

        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);

    }

}

